/**
 * 仪表板控制器
 *
 * @author songxinfeng
 * @email sxf02615@163.com  
 * @date 2025/1/15
 */
package com.sxf.crm.controller;

import com.sxf.crm.repository.CustomerRepository;
import com.sxf.crm.repository.ClueRepository;
import com.sxf.crm.repository.VisitRepository;
import com.sxf.crm.repository.ContactRepository;
import com.sxf.crm.repository.OpportunityRepository;
import com.sxf.crm.enums.ClueStatus;
import com.sxf.crm.enums.CustomerStatus;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;

/**
 * 仪表板统计数据控制器
 *
 * @author songxinfeng
 * @date 2025/1/15
 */
@RestController
@RequestMapping("/api/dashboard")
@RequiredArgsConstructor
public class DashboardController {

    private final CustomerRepository customerRepository;
    private final ClueRepository clueRepository;
    private final VisitRepository visitRepository;
    private final ContactRepository contactRepository;
    private final OpportunityRepository opportunityRepository;

    // @PreAuthorize("hasAuthority('dashboard:view') or hasRole('ADMIN') or hasRole('SALES')")
    @GetMapping("/stats")
    public ResponseEntity<Map<String, Object>> getDashboardStats() {
        Map<String, Object> stats = new HashMap<>();
        
        try {
            // 客户总数（已审核通过的）
            long customerCount = customerRepository.countByStatus(CustomerStatus.APPROVED);
            stats.put("customerCount", customerCount);
            
            // 线索总数（未回收的）
            long clueCount = clueRepository.countByStatusNotIn(
                Arrays.asList(ClueStatus.RECYCLED, ClueStatus.AUTO_RECYCLED)
            );
            stats.put("clueCount", clueCount);
            
            // 本月拜访数量
            LocalDateTime startOfMonth = LocalDateTime.now().withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
            LocalDateTime endOfMonth = startOfMonth.plusMonths(1);
            long startTimestamp = startOfMonth.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            long endTimestamp = endOfMonth.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            
            long monthlyVisitCount = visitRepository.countByVisitTimeBetween(startTimestamp, endTimestamp);
            stats.put("monthlyVisitCount", monthlyVisitCount);
            
            // 转化率（已转化线索数 / 总线索数）
            long convertedClueCount = clueRepository.countByStatus(ClueStatus.CONVERTED);
            long totalClueCount = clueRepository.count();
            double conversionRate = totalClueCount > 0 ? (double) convertedClueCount / totalClueCount * 100 : 0.0;
            stats.put("conversionRate", Math.round(conversionRate * 100.0) / 100.0); // 保留2位小数
            
            // 联系人总数
            long contactCount = contactRepository.count();
            stats.put("contactCount", contactCount);
            
            // 商机总数
            long opportunityCount = opportunityRepository.count();
            stats.put("opportunityCount", opportunityCount);
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            // 发生错误时返回默认值
            stats.put("customerCount", 0);
            stats.put("clueCount", 0);
            stats.put("monthlyVisitCount", 0);
            stats.put("conversionRate", 0.0);
            stats.put("contactCount", 0);
            stats.put("opportunityCount", 0);
            
            return ResponseEntity.ok(stats);
        }
    }
}